package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 描述:56. 合并区间
 *
 * @author Madison You
 * @created 17:02
 */
public class Mid_56_Merge {

    public static void main(String[] args) {
        int[] int1 = {1,4};
        int[] int2 = {0,4};
        int[] int3 = {8,10};
        int[] int4 = {15,18};
        int[][] aa = new int[4][2];
        aa[0] = int1;
        aa[1] = int2;
        aa[2] = int3;
        aa[3] = int4;
        int[][] merge = new Mid_56_Merge().merge(aa);
        for (int[] ints : merge) {
            System.out.println(Arrays.toString(ints));
        }
    }




    public int[][] merge(int[][] intervals) {

        if (intervals.length == 0) {
            return new int[0][2];
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            public int compare(int[] interval1, int[] interval2) {
                return interval1[0] - interval2[0];
            }
        });
        List<int[]> merged = new ArrayList<>();
        for (int i = 0; i < intervals.length; ++i) {
            int start = intervals[i][0];
            int end = intervals[i][1];
            if (merged.size() == 0 || merged.get(merged.size() - 1)[1] < start) {
                merged.add(new int[]{start, end});
            } else {
                merged.get(merged.size() - 1)[1] = Math.max(end, merged.get(merged.size() - 1)[1]);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }


}
